import {defineStore} from 'pinia';
import {computed, ref} from 'vue';
import {getCartAPI, delCartAPI, addCartAPI, updateCartAPI} from '@/apis/cart';
import { ElMessage } from 'element-plus';
// import { useUserStore } from './user'
// import { insertCartAPI } from '@/apis/cart'
// import { findNewCartListAPI } from '@/apis/cart';
// import { delCartAPI } from '@/apis/cart';


export const useCartStore=defineStore('cart', () => {
//   const userStore = useUserStore()
//   const isLogin = computed(() => userStore.userInfo.token)
// const cartList = ref([]);
// const addCart = async (goods) => {
//   const { skuId, count } = goods
//   if (isLogin.value) {
//     // 登录之后的加入购车逻辑
//     await insertCartAPI({ skuId, count })
//     const res = await findNewCartListAPI()
//     cartList.value = res.result
//   } else {
//     // 登录之前的加入购车逻辑
//     const item = cartList.value.find((item) => goods.skuId === item.skuId)
//     if (item) {
//       // 找到了
//       item.count++
//     } else {
//       // 没找到
//       cartList.value.push(goods)
//     }
//   }

const cartList = ref([]);

// 添加购物车
const addCart = async (goods) => {
  if (!goods || !goods.skuId) {
    ElMessage.warning('商品信息不完整');
    return;
  }
  
  try {
    // 调用后端API添加到购物车
    const res = await addCartAPI({
      skuId: goods.skuId,
      count: goods.count || 1,
      price: goods.price,
      attrsText: goods.attrsText || '默认规格'
    });
    
    if (res.data && res.data.code === 200) {
      // 重新获取购物车列表
      await getCartList();
      ElMessage.success('添加购物车成功');
    } else {
      console.error('添加购物车响应异常', res);
      ElMessage.error('添加购物车失败');
      // 失败时本地添加
      const item = cartList.value.find((item) => goods.skuId === item.skuId);
      if (item) {
        item.count += 1;
      } else {
        cartList.value.push(goods);
      }
    }
  } catch (error) {
    console.error('添加购物车失败', error);
    ElMessage.error('添加购物车失败');
    // 失败时本地添加
    const item = cartList.value.find((item) => goods.skuId === item.skuId);
    if (item) {
      item.count += 1;
    } else {
      cartList.value.push(goods);
    }
  }
};

// 获取购物车列表
const getCartList = async () => {
  try {
    const res = await getCartAPI();
    console.log('购物车API返回数据:', res);
    
    if (res && res.data && res.data.code === 200) {
      if (Array.isArray(res.data.result)) {
        // 确保每个商品都有selected属性
        cartList.value = res.data.result.map(item => ({
          ...item,
          id: item.id,
          name: item.name || '商品',
          price: item.price || 0,
          count: item.count || 1,
          image: item.image || 'https://example.com/default.jpg',
          selected: item.selected === true || item.selected === 1
        }));
        console.log('购物车数据加载成功，共', cartList.value.length, '个商品');
      } else {
        console.log('购物车数据格式不正确', res.data.result);
        ElMessage.warning('购物车数据格式不正确');
      }
    } else {
      console.log('获取购物车数据响应异常', res);
      ElMessage.warning('获取购物车数据响应异常');
    }
  } catch (error) {
    console.error('获取购物车数据失败', error);
    ElMessage.error('获取购物车数据失败');
  }
};

//删除购物车
const delCart = async (id) => {
  if (!id) {
    ElMessage.warning('商品ID不能为空');
    return;
  }
  
  try {
    const res = await delCartAPI(id);
    if (res.data && res.data.code === 200) {
      // 重新获取购物车列表
      await getCartList();
      ElMessage.success('删除成功');
    } else {
      console.error('删除购物车商品响应异常', res);
      ElMessage.error('删除购物车商品失败');
      // 删除本地数据
      const idx = cartList.value.findIndex(item => item.id === id);
      if (idx > -1) {
        cartList.value.splice(idx, 1);
      }
    }
  } catch (error) {
    console.error('删除购物车商品失败', error);
    ElMessage.error('删除购物车商品失败');
    // 删除本地数据
    const idx = cartList.value.findIndex(item => item.id === id);
    if (idx > -1) {
      cartList.value.splice(idx, 1);
    }
  }
};

// 更新购物车列表（清空已购买商品）
const updateNewList = async () => {
  try {
    // 清除已选择的商品
    cartList.value = cartList.value.filter(item => !item.selected);
  } catch (error) {
    console.error('更新购物车失败', error);
    ElMessage.error('更新购物车失败');
  }
}

//清除购物车
const clearCart = () => {
  cartList.value = []
}

//单选
const singleCheck = async (id, selected) => {
  const item = cartList.value.find((item) => item.id === id);
  if (item) {
    item.selected = selected;
    try {
      // 这里可以添加更新商品选中状态的API调用
      const res = await updateCartAPI(id, { selected: selected ? 1 : 0 });
      if (!res.data || res.data.code !== 200) {
        console.error('更新商品状态响应异常', res);
      }
    } catch (error) {
      console.error('更新商品状态失败', error);
    }
  }
};

//计算属性
const allCount = computed (() => {
  return cartList.value.reduce((total, item) => {
    return total + (item.count || 0);
  }, 0);
})

const allPrice =computed (() => {
  return cartList.value.reduce((total, item) => {
    return total + (item.price || 0) * (item.count || 0);
  }, 0);
})

//是否全选
const allCheck = (selected) => {
  cartList.value.forEach(item => item.selected = selected)
}

// 是否全选计算属性
const isAll = computed(() => cartList.value.length > 0 && cartList.value.every((item) => item.selected))

// 3. 已选择数量
const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + (c.count || 0), 0))
// 4. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + (c.count || 0) * (c.price || 0), 0))



return {
  cartList,
  addCart,
  delCart,
  getCartList,
  updateNewList,
  allCount,
  allPrice,
  singleCheck,
  allCheck,
  isAll,
  selectedCount,
  selectedPrice,
  clearCart
};
},{
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage,
      },
    ],
  },
  name: 'cart',
});
